import urlConfig from './config.js';

const request = {};
const headers = {};

request.globalRequest = (url, method, data, power) => {
	/*     权限判断 因为有的接口请求头可能需要添加的参数不一样，所以这里做了区分 */
	switch (power) {
		case 1:
			headers['Content-Type'] = 'application/json';
			break;
		default:
			headers['Content-Type'] = 'application/x-www-form-urlencoded';
			break;
	}

	// 请求头携带的登录凭证
	headers['x-auth-token'] = uni.getStorageSync('authToken');

	let baseUrl = urlConfig;
	// H5页面跨域访问处理
	// #ifdef H5
	baseUrl = '/api';
	// #endif
	return uni
		.request({
			url: baseUrl + url,
			method,
			data: data,
			dataType: 'json',
			header: headers,
		})
		.then((res) => {
			// 返回请求结果
			return res[1];
		})
		.catch((parmas) => {
			switch (parmas.code) {
				case 401:
					uni.clearStorageSync();
					break;
				default:
					uni.showToast({
						title: parmas.message,
						icon: 'none',
					});
					return Promise.reject();
			}
		});
};

export default request;
